package com.bolt.report.engine.fill;

import com.bolt.common.reflect.ObjectUtil;
import com.bolt.common.utils.JacksonUtil;
import com.bolt.common.utils.StrUtil;
import com.bolt.report.definition.StyleDefinition;
import com.bolt.report.engine.FillElementVisitor;
import com.bolt.report.engine.model.Cell;
import com.bolt.report.engine.model.Expression;
import com.bolt.report.util.GoogleBarCodeUtil;
import com.fasterxml.jackson.databind.JsonNode;

import java.nio.charset.Charset;
import java.util.Map;

public class CellElementVisitor implements FillElementVisitor<Cell> {


    @Override
    public void visit(FillTextElement element, Cell cell) {
        executeExpr(element, cell);
    }

    @Override
    public void visit(FillCodeImageElement barCodeElement, Cell cell) {
        Expression expr = barCodeElement.getExpr();
        Object value = expr.execute(barCodeElement.getFillContext(), cell);
        if (ObjectUtil.isNotNull(value)) {
            Map<String, Object> option = JacksonUtil.toMap(barCodeElement.getJsonData().toString());
            option.put("width", barCodeElement.getWidth());
            option.put("height", barCodeElement.getHeight());
            String image = GoogleBarCodeUtil.createCode((String) value, barCodeElement.getType().name(), option);
            barCodeElement.setValue(image);
            cell.getStyle().setWidth(barCodeElement.getWidth());
            cell.getStyle().setHeight(barCodeElement.getHeight());
        }
    }


    @Override
    public void visit(FillImageElement imageElement, Cell cell) {
        if (StrUtil.isBlank(imageElement.getValue())) {
            String data = (String) imageElement.getBindData().getData();
            if (StrUtil.startWith(data, "data:image")) {
                imageElement.setValue(data);
            } else if (StrUtil.startWith(data, "http")) {

            } else {

            }
        }
    }

    @Override
    public void visit(FillDataSetElement element, Cell cell) {
        executeExpr(element, cell);
    }

    public void executeExpr(BaseFillElement element, Cell cell) {
        if (element.getExpr().isExecute()) {
            Expression expression = element.getExpr();
            Object value = expression.execute(element.getFillContext(), cell);
            element.setValue(StrUtil.str(value, Charset.defaultCharset()));
        }
    }

    @Override
    public void visit(FillChartElement fillChartElement, Cell cell) {
        JsonNode jsonData = fillChartElement.getJsonData();
        fillChartElement.setChartId(jsonData.get("chartId").asText());
        fillChartElement.setWidth(jsonData.get("width").asInt());
        fillChartElement.setHeight(jsonData.get("height").asInt());
        StyleDefinition style = new StyleDefinition();
        style.setWidth(fillChartElement.getWidth());
        style.setHeight(fillChartElement.getHeight());
        cell.setStyle(style);
    }
}